#!/usr/bin/python3
# -*- coding: utf-8 -*-

import socket, json, requests ,subprocess as sup
import time, hmac, hashlib, base64, urllib.parse
from threading import Timer

#*******************客户端*********************#
#                                              #
#**********************************************#
S_socket = None

#服务器IP和端口
HOST = '120.xxx.xxx.xxx'
POST = 8080

#命令列表
command = ['时间', '服务器状态']

#机器人WebHook
Webhook = 'https://oapi.dingtalk.com/robot/send?access_token=xxx'

#心跳程序，断线自动重新连接
def heartbeat():
    global S_Socket
    data ={"time" : round(time.time() * 1000)}
    #print(S_Socket)
    try:
        S_Socket.send(bytes(json.dumps(data),'utf-8'))
    except Exception as err:
        print("[%s]连接中断，正在重新连接。。。"%err)
        try:
            ss = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            ss.connect((HOST,POST))
            S_Socket = ss
            LoginInfo = 'Dingding\r\n' + socket.gethostname()
            S_Socket.send(bytes(LoginInfo, 'utf-8'))
        except Exception as err:
            print("[%s]连接错误：5秒后重新连接。。。"%err)
    t = Timer(15, heartbeat, )
    t.start()

#OutGoing消息处理
def MSMQ(msg):
    try:
        msgdata = json.loads(msg.decode('utf-8'))
       #print(msgdata)
        print(msgdata['text']['content'])
    except Exception as err:
        print(msg.decode('utf-8'))
        return
    if msgdata['text']['content'].strip() == command[0]:
        message = '<font color=#A50000 size=6 face="黑体"> 时间 </font>\n' +\
                  '> ' + time.strftime("现在是：%Y-%m-%d %H:%M:%S", time.localtime())
        DingBot(command[0],message)
    if msgdata['text']['content'].strip() == command[1]:
        info = sup.getoutput('/DietPi/dietpi/dietpi-cpuinfo')
        message = '<font color=#A50000 size=6 face="黑体"> 主机状态 </font>\n' +\
                  '> ' + info
        DingBot(command[1],message)

#机器人发送消息 MarkDown格式
def DingBot(Title, Message):

    url = Sign()

    headers = {'Content-Type': 'application/json; charset=utf-8'}

    _data = {
        "msgtype": "markdown",
        "markdown": {
            "title": Title,
            "text": Message
        }
    }

    data = json.dumps(_data)

    response = requests.post(url=url, headers=headers, data=data)
    result = response.json()
    print(result, _data)
    return result

#签名
def Sign():
    timestamp = int(round(time.time() * 1000))
    secret = 'xxxxxx'
    secret_enc = bytes(secret, 'utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = bytes(string_to_sign, 'utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    print(timestamp, sign)
    return Webhook + '&timestamp=' + str(timestamp) + '&sign=' + sign


if __name__ == '__main__':
    #print(Sign())
    global S_Socket
    S_Socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        S_Socket.connect((HOST,POST))
    except Exception as err:
        print("连接建立失败:%s" % err)
        exit()
    LoginInfo = 'Dingding\r\n' + socket.gethostname()
    S_Socket.send(bytes(LoginInfo, 'utf-8'))
    heartbeat()
    while True:
        data = S_Socket.recv(1024)
        if data !=  b'':
            MSMQ(data)
       # else:
       #     print('连接已断开')
       #     message = '<font color=#A50000 size=6 face="黑体"> 连接错误 </font>\n' +\
       #           '> ' + '与服务器断开连接'
       #     DingBot('连接错误',message)
       #     S_Socket.close()
       #     break

